/**
 *
 */
package com.linkage.im.processor;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.linkage.im.model.UserVo;
import com.linkage.common.util.RedisUtils;
import com.linkage.im.utils.SpringUtil;
import com.linkage.im.utils.UserInterfUtils;
import org.jim.common.*;
import org.jim.common.cache.redis.RedisCacheManager;
import org.jim.common.message.MessageHelper;
import org.jim.common.packets.*;
import org.jim.common.utils.JsonKit;
import org.jim.server.command.CommandManager;
import org.jim.server.command.handler.JoinGroupReqHandler;
import org.jim.server.command.handler.processor.login.LoginCmdProcessor;
import org.jim.server.helper.redis.RedisMessageHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tio.core.ChannelContext;

import javax.annotation.Resource;
import java.util.*;

/**
 * @author WChao
 *
 */
public class LoginServiceProcessor implements LoginCmdProcessor {

	private Logger logger = LoggerFactory.getLogger(LoginServiceProcessor.class);

	@Resource
	private RedisUtils redisUtils;

	/**
	 * 根据用户名和密码获取用户
	 * @param loginname
	 * @param password
	 * @return
	 * @author: WChao
	 */
	public User getUser(String loginname, String password,String flag) {
		Map returnBuss = UserInterfUtils.login(loginname,password,flag);
		this.logger.info("获取到用户token为：" + returnBuss.get("usertoken"));
		return getUser(UserVo.builder().userCode(returnBuss.get("userCode").toString()).build(),returnBuss.get("usertoken").toString());
	}
	/**
	 * 根据token获取用户信息
	 * @param token
	 * @return
	 * @author: WChao
	 */
	public User getUser(UserVo userInfo, String token) {
		if (null == this.redisUtils) {
			this.redisUtils = (RedisUtils) SpringUtil.getBean("redisUtils");
		}
//		User user = RedisCacheManager.getCache("user").get(userInfo.getUserCode()+":info", User.class);
//		if (null == user) {
		UserVo userVo = UserInterfUtils.getUserInfo(userInfo.getUserCode(), token);
		User user = new User();
		user.setId(userVo.getUserCode());
		user.setNick(userVo.getUserRealName());
		user.setGroups(initGroups(userVo.getPersonOrgCode(), userVo.getPersonOrgName(),userVo.getUserCode()));
		user.setFriends(initFriends(token,userVo.getPersonOrgCode(), userVo.getPersonOrgName()));
		user.setExtras(JSONObject.parseObject(JSON.toJSONString(userVo)));
		return user;
//		}
//		return user;
	}

	public List<Group> initGroups(String dptCode,String dptName,String userCode){
        // 根据用户id查询缓存中的群组
        MessageHelper messageHelper = new RedisMessageHelper();
        List<Group> groupList = messageHelper.getAllGroupUsers(userCode,2);
        if(ObjectUtil.isEmpty(groupList)){
			groupList = new ArrayList<>();
			Group group = new Group();
			group.setGroup_id(dptCode);
			group.setName(dptName);
			groupList.add(group);
        }
		return groupList;
	}

	public List<Group> initFriends(String token, String dptCode,String dptName){
		// 根据用户ID查询部门所有用户
		List<Group> friends = new ArrayList<Group>();
		List<UserVo> userVoList = UserInterfUtils.getUserListByDptCode(dptCode, token);
		if(ObjectUtil.isEmpty(userVoList)){
			return null;
		}
		for (UserVo userVo: userVoList){
			Group myFriend = new Group(dptCode,dptName);
			List<User> myFriendGroupUsers = new ArrayList<User>();
			User user1 = new User();
			user1.setId(userVo.getUserCode());
			user1.setNick(userVo.getUserRealName());
			user1.setAvatar(userVo.getUserPhotoUrl());
			user1.setExtras(JSONObject.parseObject(JSON.toJSONString(userVo)));
			myFriendGroupUsers.add(user1);
			myFriend.setUsers(myFriendGroupUsers);
			friends.add(myFriend);
		}
		return friends;
	}

	/**
	 * doLogin方法注意：J-IM登陆命令是根据user是否为空判断是否登陆成功,
	 *
	 * 当登陆失败时设置user属性需要为空，相反登陆成功user属性是必须非空的;
	 */
	@Override
	public LoginRespBody doLogin(LoginReqBody loginReqBody , ChannelContext channelContext) {
		String loginname = loginReqBody.getLoginname();
		String password = loginReqBody.getPassword();
		String flag = loginReqBody.getToken();
		User user;
		LoginRespBody loginRespBody;
		user = this.getUser(loginname, password,flag);
		if(ObjectUtil.isEmpty(user.getGroups())){
			MessageHelper messageHelper = CommandManager.getImConfig().getMessageHelper();
			user.setGroups(messageHelper.getAllGroupUsers(user.getId(),0));
		}
		if(user == null){
			loginRespBody = new LoginRespBody(Command.COMMAND_LOGIN_RESP,ImStatus.C10008);
		}else{
			loginRespBody = new LoginRespBody(Command.COMMAND_LOGIN_RESP,ImStatus.C10007,user);
		}
		return loginRespBody;
	}

	@Override
	public void onSuccess(ChannelContext channelContext) {
		logger.info("登录成功回调方法");
		ImSessionContext imSessionContext = (ImSessionContext)channelContext.getAttribute();
		User user = imSessionContext.getClient().getUser();
		if(user.getGroups() != null){
			for(Group group : user.getGroups()){//发送加入群组通知
				ImPacket groupPacket = new ImPacket(Command.COMMAND_JOIN_GROUP_REQ,JsonKit.toJsonBytes(group));
				try {
					JoinGroupReqHandler joinGroupReqHandler = CommandManager.getCommand(Command.COMMAND_JOIN_GROUP_REQ, JoinGroupReqHandler.class);
					joinGroupReqHandler.joinGroupNotify(groupPacket, channelContext);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}

	@Override
	public boolean isProtocol(ChannelContext channelContext) {

		return true;
	}

	@Override
	public String name() {

		return "default";
	}
}
